package com.marvels.product.productmanage.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.marvels.common.exception.MarvelsBusinessException;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.product.productmanage.dao.ProductTypeDao;
import com.marvels.product.productmanage.dto.FeeRateDTO;
import com.marvels.product.productmanage.service.ParamsAchieveService;
@Service
public class ParamsAchieveServiceImpl implements ParamsAchieveService {
	@Autowired
	private ProductTypeDao productTypeDao;
	@Value("${config.properties.path}")
	private String filePath;
	@Override
	public Map<String,Object> feeRateAndManagementExpense(FeeRateDTO feeRateDto) throws MarvelsBusinessException {
		if(feeRateDto==null) throw new MarvelsBusinessException("获取费率入参为空");
		MarvelsLogUtil.getInstance().info("获取费率入参=======》》》》》："+feeRateDto.toString());
		//配置开关
		String switchFlag = ServerProperties.getValue(filePath, "resource.properties", "product.feeRate.isValid");
		Map<String,Object> result = new HashMap<String,Object>();
		if("Y".equals(switchFlag)){
			if(StringUtils.isEmpty(feeRateDto.getChannel())){
				throw new MarvelsBusinessException("渠道为空");
			}
			if(StringUtils.isEmpty(feeRateDto.getProductType())){
				throw new MarvelsBusinessException("产品类型为空");
			}
			List<FeeRateDTO> feeRates =  productTypeDao.getFeeRate(feeRateDto);
			if(CollectionUtils.isEmpty(feeRates)){
				throw new MarvelsBusinessException("费率未配置");
			}
			//去重设置评级编码
			Set<String> grateSet = new HashSet<String>();
			for (FeeRateDTO feeRate : feeRates) {
				grateSet.add(feeRate.getGrate());
			}
			//组装返回参数
			for (String grate : grateSet) {
				List<FeeRateDTO> list = new LinkedList<FeeRateDTO>();
				for (FeeRateDTO dto : feeRates) {
					if(grate.equals(dto.getGrate())){
						list.add(dto);
					}
				}
				result.put(grate, list);
			}
			result.put("isNew", false);
			MarvelsLogUtil.getInstance().info("获取费率出参=======》》》》》："+result);
		}else{
			MarvelsLogUtil.getInstance().info("获取费率出参=======》》》》》："+result);
			MarvelsLogUtil.getInstance().info("获取费率出参开关未打开=======》》》》》："+switchFlag);
		}
		return result;
	}
}
